package it.evento.manager;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.plus.PlusScopes;

import java.io.IOException;
import java.util.Arrays;

/**
 *
 * @author Ilo
 */
public class OAuthManager {

    private static HttpTransport httpTransport;
    private static JacksonFactory jsonFactory;
    private static final String clientId = "1092245667811-76m5r5eet5qp6v0phfvahs13865122ii.apps.googleusercontent.com";
    private static final String clientSecret = "fORJoygqL6qlrY7vzYoEbS8D";
    private static GoogleAuthorizationCodeFlow flow;
    private static String redirectUrl;
    private static GoogleCredential credential;

    public OAuthManager() {
        httpTransport = new NetHttpTransport();
        jsonFactory = new JacksonFactory();
        
        redirectUrl = "http://localhost:8080/ProgettoEvenTo-war/OAuthController";

        flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, clientId, clientSecret,
                Arrays.asList(CalendarScopes.CALENDAR, 
                              PlusScopes.PLUS_LOGIN))
                    .setAccessType("online")
                    .setApprovalPrompt("auto").build();
    }

    // Read the authorization code 
    public void genCredential(String code) throws IOException {
        System.out.println("flow: " + flow);
        
        GoogleTokenResponse responseGoogle = flow.newTokenRequest(code)
                .setRedirectUri(redirectUrl).execute();
        credential = new GoogleCredential()
                .setFromTokenResponse(responseGoogle);
        
        System.out.println(" response: " + responseGoogle);
    }

    public HttpTransport getHttpTransport() {
        return httpTransport;
    }

    public JacksonFactory getJsonFactory() {
        return jsonFactory;
    }

    public GoogleAuthorizationCodeFlow getFlow() {
        return flow;
    }

    public String getRedirectUrl() {
        return redirectUrl;
    }

    public GoogleCredential getCredential() {
        return credential;
    }
    
}
